package com.star.controller.user;

import com.star.constant.JwtClaimsConstant;
import com.star.context.BaseContext;
import com.star.dto.UserDTO;
import com.star.dto.UserLoginCodeDTO;
import com.star.dto.UserRegisterDTO;
import com.star.dto.UserLoginDTO;
import com.star.entity.User;
import com.star.properties.JwtProperties;
import com.star.result.Result;
import com.star.service.UserService;
import com.star.utils.JwtUtil;
import com.star.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user/user")
@Slf4j
@Api(tags = "C端用户相关接口")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private RedisTemplate<String, User> userRedisTemplate;
    @Autowired
    private RedisTemplate<String, String> stringRedisTemplate;

    @PostMapping("/login")
    @ApiOperation("登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("用户登录{}",userLoginDTO);
        User user = userService.login(userLoginDTO);
        // 生成jwt令牌
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        log.info("claims{}",claims);
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        // 将用户信息缓存到redis中
        stringRedisTemplate.opsForValue().set("user_token",token,60, TimeUnit.MINUTES);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .name(user.getName())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }

    @PostMapping("/code")
    @ApiOperation("获取验证码")
    public Result<String> code (@RequestBody String phone) {
        if (!phone.matches("^1[3-9]\\d{9}$")) {
            return Result.error("手机号格式不正确");
        }
        // 随机生成6位数验证码
        String code = String.format("%06d", new Random().nextInt(1000000));
        // 保存到redis中
        stringRedisTemplate.opsForValue().set(
                phone,
                code,
                5,
                TimeUnit.MINUTES
        );
        return Result.success(code);
    }

    @PostMapping("/login/code")
    @ApiOperation("验证码登录")
    public Result<UserLoginVO> loginByCode(@RequestBody UserLoginCodeDTO userLoginCodeDTO){
        User user = userService.loginByCode(userLoginCodeDTO);
        // 生成jwt令牌
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        log.info("claims{}",claims);
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        // 将用户信息缓存到redis中
        stringRedisTemplate.opsForValue().set("user_token",token,60, TimeUnit.MINUTES);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .name(user.getName())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }
    /**
     * 新增用户
     * @param userRegisterDTO body参数
     * @return
     */
    @PostMapping("/register")
    @ApiOperation("新增用户")
    public Result<String> register(@RequestBody UserRegisterDTO userRegisterDTO) {
        log.info("新增用户{}", userRegisterDTO);
        userService.add(userRegisterDTO);
        return Result.success();
    }
    /**
     * 退出
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation("用户登出")
    public Result<String> logout() {
        log.info("用户已登出");

        // 清除redis缓存
        String key = "user_" + BaseContext.getCurrentId();
        clearUser(key);
        return Result.success();
    }



    /**
     * 根据id查询用户信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询用户信息")
    public Result<User> getById(@PathVariable Long id){
        log.info("用户id{}", id);
        String key = "user_" + id;

        // 尝试从Redis中获取用户信息
        User userFromRedis = userRedisTemplate.opsForValue().get(key);
        if (userFromRedis != null) {
            log.info("从Redis中获取用户信息成功");
            return Result.success(userFromRedis);
        }

        // 如果Redis中没有，则从数据库中获取
        User user = userService.getById(id);

        userRedisTemplate.opsForValue().set(key, user);
        return Result.success(user);
    }
    /**
     * 更新用户信息
     * @param userDTO body参数
     * @return
     */
    @PutMapping
    @ApiOperation("更新用户信息")
    public Result<String> update(@RequestBody UserDTO userDTO){
        log.info("更新用户信息{}", userDTO);
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        userService.update(user);

        // 清除redis缓存
        String key = "user_" + userDTO.getId();
        clearUser(key);
        return Result.success();
    }
    /**
     * 修改用户头像
     * @param avatar
     * @return
     */
    @PutMapping("/avatar")
    public Result<String> updateAvatar(@RequestParam Long id, @RequestParam String avatar){
        if(avatar == null || avatar.isEmpty()){
            return Result.error("头像不能为空");
        }
        User user = new User();
        user.setId(id);
        user.setAvatar(avatar);
        userService.update(user);

        // 清除redis缓存
        String key = "user_" + id;
        clearUser(key);
        return Result.success();
    }
    /**
     * 清除redis缓存数据
     * @param pattern
     */
    private void clearUser(String pattern){
        Set<String> keys = userRedisTemplate.keys(pattern);
        if(keys != null){
            userRedisTemplate.delete(keys);
        }
    }
}
